<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Get</h1>
    <button onclick="get()">GET</button>
    <h1> Post by text/plain </h1>
    <form action="/postData" method="POST" enctype="text/plain" onsubmit="post(this);return false;">
      <p>Name: <input type="text" name="user" /></p>
      <p>Message: <input type="text" name="message" /></p>
      <p><button type="submit">提交</button></p>
    </form>
    <h1> Post by application/x-www-form-urlencoded </h1>
    <form action="/postData" method="POST" enctype="application/x-www-form-urlencoded" onsubmit="post(this);return false;">
      <p>Name: <input type="text" name="user" /></p>
       <p>password: <input type="text" name="password" /></p>
      <p><button type="submit">提交</button></p>
    </form>

    <h1> Post by multipart/form-data </h1>
    <form action="/upload" method="POST" enctype="multipart/form-data" onsubmit="postFile(this);return false;">
       <p>Your Files: <input type="file" multiple name="file" /></p>
      <p><button type="submit">提交</button></p>
    </form>
    <script>
      if (!XMLHttpRequest.prototype.sendAsBinary) {
        XMLHttpRequest.prototype.sendAsBinary = function(sData) {
          var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
          for (var nIdx = 0; nIdx < nBytes; nIdx++) {
            ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
          }
          /* send as ArrayBufferView...: */
          this.send(ui8Data);
          /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
        };
      }
      function plainEscape (text) {
        return text.replace(/[\s\=\\]/g, '\\$&');
      }
      function post(target) {
        const httpRequest = new XMLHttpRequest();
        httpRequest.onload = function() {
          alert(this.responseText);
        }
        httpRequest.open(target.method, target.action, true);
        const data = [];
        let enctype = target.enctype === 'text\/plain' ? 
        0 : target.enctype === 'application\/x-www-form-urlencoded' ?
        1 : 2;
        httpRequest.setRequestHeader('Content-Type', enctype);
        for (let i=0 ; i < target.elements.length; i += 1) {
          let field = target.elements[i];
          if (!field.hasAttribute("name")) continue;
          data.push(plainEscape(field.name) + '=' + plainEscape(field.value));
        }
        httpRequest.send(enctype === 0 ? data.join('\r\n') : data.join('&'));
      }

      function postFile(target) {

        const uploadNow = function(field) {
          const boundary = '---------------------------' + Date.now().toString(16);
          const httpRequest = new XMLHttpRequest();
          httpRequest.onload = function() {
            alert(this.responseText);
          }
          httpRequest.open(target.method, target.action, true);
          httpRequest.setRequestHeader('Content-Type', 'multipart\/form-data; boundary=' + boundary);
          httpRequest.sendAsBinary('--' + boundary + '\r\n' 
          + field.segments.join('--' + boundary + '\r\n')
          + '--' + boundary + '--\r\n');

        }

        function fileloadSuccess(evt) {
          this.field.segments[this.fileId] += evt.target.result + '\r\n';
          this.field.status -= 1;
          if (this.field.status === 0) {
            uploadNow(this.field);
          }
        }

        
        for (let i = 0; i < target.elements.length; i += 1) {
          let field = target.elements[i];
          field.segments = [];
          field.status = 0;
          if (!field.hasAttribute('name')) continue;
          if (field.type.toUpperCase() === 'FILE' && field.files.length > 0) {
            for (let j = 0; j < field.files.length; j += 1) {
              let file = field.files[j];
              let reader = new FileReader();
              reader.onload = fileloadSuccess;
              reader.fileId = j;
              field.status += 1;
              field.segments.push('Content-Disposition: form-data; name=\"' 
              + field.name + '\"; filename=\"' 
              + file.name + '\"\r\nContentType: ' 
              + file.type + '\r\n\r\n');
              reader.field = field;
              reader.readAsBinaryString(file);
            }
          }
        }
      }




      function get() {
        const httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function deal() {
         if (httpRequest.readyState === XMLHttpRequest.DONE) {
           if (httpRequest.status === 200) {
             alert(httpRequest.responseText);
           }
         }
        }

        // httpRequest.addEventListener('progress', function(event) {
        //   console.log(event);
        // }, false);
        // httpRequest.addEventListener('load', function(event) {
        //   console.log(event);
        // }, false);
        // httpRequest.addEventListener('error', function(event) {
        //   console.log(event);
        // }, false);
        // httpRequest.addEventListener('abort', function(event) {
        //   console.log(event);
        // }, false);

        var param = new URLSearchParams();
        param.set('hello', 'you');
        for(let k of param) {
          console.log(k);
        }
        httpRequest.open('GET', 'http://localhost:8080?'+ param.toString(), true);
        httpRequest.setRequestHeader('Accept', 'text/plain');
        httpRequest.send();
      }
    </script>
  </body>
</html>